//
//  USMainHomeToolBar.m
//  us
//
//  Created by karry on 2025/4/23.
//

#import "USMainHomeToolBar.h"
#import "USMainHomeToolBarItemCell.h"

@interface USMainHomeToolBar()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic,strong)UICollectionView *collectionView;

@end

@implementation USMainHomeToolBar

- (instancetype)initWithFrame:(CGRect)frame items:(NSArray <DTItem *>*)items{
    if (self = [super initWithFrame:frame]) {
        _items = items;
        [self setupView];
    }
    return self;
}

- (void)setupView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize;
    layout.minimumInteritemSpacing = 16;
    layout.minimumLineSpacing = 16;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(0, 16, 0, 16);
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:layout];
    self.collectionView = collectionView;
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.showsHorizontalScrollIndicator = NO;
    [collectionView registerNib:[UINib nibWithNibName:@"USMainHomeToolBarItemCell" bundle:nil] forCellWithReuseIdentifier:@"USMainHomeToolBarItemCellId"];
    collectionView.backgroundColor = UIColor.clearColor;
    [self addSubview:collectionView];
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    self.backgroundColor = [UIColor clearColor];
    
}

- (void)setItems:(NSArray<DTItem *> *)items{
    _items = items;
    [self.collectionView reloadData];
}

#pragma mark - <UICollectionViewDataSource,UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [USFeedbackTool impactSoft];
    
    DTItem *item = self.items[indexPath.row];
    !item.handler?:item.handler(item);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.items.count;
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    DTItem *item = self.items[indexPath.row];
    
    USMainHomeToolBarItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USMainHomeToolBarItemCellId" forIndexPath:indexPath];
    
    cell.imageV.image = item.image;
    
    cell.lab.text = item.title;
    
    cell.tagView.hidden = item.tag == 1?NO:YES;
    
    return cell;
    
}

@end
